package hn.cch.advanced.concurrent.atomic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * LongAdder比AtomicLong性能好
 */
public class LongAdderDemo {

    private static final Logger logger = LoggerFactory.getLogger(LongAdderDemo.class);


    private AtomicLong atomicLong;
    private LongAdder longAdder;

    public void addAtomicLong(long add) {
        atomicLong.addAndGet(add);
    }

    public void addLongAdder(long add) {
        longAdder.add(add);

    }


    public static void main(String[] args) {
        long add = 1L;
        LongAdderDemo demo = new LongAdderDemo();
        demo.atomicLong = new AtomicLong();
        demo.longAdder = new LongAdder();
        int n = 1000;
        ExecutorService threadPool = Executors.newFixedThreadPool(n);
        logger.debug("start");
        for (int i = 0; i < n; i++) {
            // threadPool.execute(() -> demo.addAtomicLong(add));
            threadPool.execute(() -> demo.addLongAdder(add));
        }

        threadPool.shutdown();
        // ThreadPoolDemo.complete(threadPool);
        // logger.debug("atomicLong:{}", demo.atomicLong.get());
        logger.debug("longAdder:{}", demo.longAdder.sum());

    }


}
